<?php
require_once 'models/publisher.inc';
require_once 'pages/TMSItemPage.inc';

/**
 * @property IItemPublisher $ItemPublisher
 * @property TCMSCategoryModel $CmsCategoriesModel
 * @property TCMSPageCategoryModel $PageCategoriesModel
 */
class TMSAdminPublicableItemPage extends TMSItemPage {	
/**
 * @var IItemPublisher
 */
	protected $_ioc_item_publisher_;
	
/**
 * @var TCMSCategoryModel
 */
	protected $_ioc_cms_categories_model_;

/**
 * @var TCMSPageCategoryModel
 */
	protected $_ioc_page_categories_model_;
	
	private $_categories_;
	
	private $_page_categories_;
	
	protected $pageItem = null;
	
	protected $_conf_frontend_root_ = "/";
	
	public function __get($nm){
		switch ($nm){
			case 'Categories':{
				if (is_null($this->_categories_))
					$this->_categories_ = $this->CmsCategoriesModel->GetContents(null,false);
				return $this->_categories_;
			}break;
			case 'PageCategories':{
				if (is_null($this->_page_categories_)){
					$this->_page_categories_ = array();
					if ($this->pageItem)
						if ($this->pageItem->ItemId())
							foreach ($this->pageItem->Categories as $category)
								$this->_page_categories_[] = $category->Id;
				}
				return $this->_page_categories_;
			}break;
			case 'FrontProductUrlQuery':{
				if (($this->ItemPublisher instanceof TCandyModel) && $this->pageItem)
					return ($this->pageItem->ItemId())?($this->FrontendRoot.'?service=json&method=ItemUrl&class='.$this->ItemPublisher->ClassName().'&id='.$this->pageItem->ItemId().'&slug='.$this->pageItem->Slug):null;
				return null;
			}break;
			default:return parent::__get($nm);break;
		}
	}	
	
	
	protected function getItem(){
		$item = parent::getItem();
		$this->pageItem = $this->ItemPublisher->ItemIssue($item);
		return $item;
	}
		
	public function ItemPage(){
		return $this->pageItem;
	}
	
	protected function doPageSave($data,$categories){
		if (!isset($data['Title']))
			$data['Title'] = $this->ModelItem->Name;
		
		if (!isset($data['IsPublished']))
			$data['IsPublished'] = false;
		
		if (!$this->pageItem){
			$this->pageItem = $this->ItemPublisher->PublishItem($this->ModelItem,array_keys($categories));
			$this->pageItem = $this->ItemPublisher->EditItem($this->pageItem->ItemId(), $data);
		} else {
			$this->pageItem = $this->ItemPublisher->EditItem($this->pageItem->ItemId(), $data);
			$this->PageCategoriesModel->MovePage($this->pageItem->Base, array_keys($categories));
		}
		return $this->pageItem;
	}
	
	public function http_PublishItem($categories = array()){
		$this->doPageSave(array(), $categories);
	}
	
	public function http_SavePage($pp,$categories = array()){
		$this->doPageSave($pp, $categories);
	}
}